package com.mini.service;

import com.mini.conditon.RangeInfoCondition;
import com.mini.config.BusinessException;
import com.mini.constant.GoalStatusEnum;
import com.mini.model.BusinessRangeInfo;
import com.mini.repository.BusinessRangeInfoRepository;
import com.mini.vo.PageResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.*;

/**
 * @author: zhaocg
 * @created: 2020/12/02 12:00
 */
@Slf4j
@Service
public class BusinessRangeInfoService extends BaseService{

    @Autowired
    private BusinessRangeInfoRepository rangeInfoRepository;


    /**
     * 获取业务范围分页数据
     *
     * @param condition
     * @return
     */
    public PageResultVO<BusinessRangeInfo> pageList(RangeInfoCondition condition){
        PageResultVO<BusinessRangeInfo> pageResultVO = new PageResultVO<>();
        Pageable pageable = buildPageRequest(condition.getPageNumber(),condition.getPageSize(),new Sort(Sort.Direction.DESC,"createTime"));

        Page<BusinessRangeInfo> page = rangeInfoRepository.findAll(this.getRangeInfoSpecification(condition) , pageable);
        if ( page != null && !CollectionUtils.isEmpty(page.getContent()) ) {
            pageResultVO.setRows(page.getContent());
            pageResultVO.setTotal(page.getTotalElements());
        }
        return pageResultVO;
    }

    /**
     * 获取符合条件的业务范围数据
     *
     * @param condition
     * @return
     */
    public List<BusinessRangeInfo> rangeInfoList(RangeInfoCondition condition){
        return rangeInfoRepository.findAll(this.getRangeInfoSpecification(condition));
    }

    private Specification<BusinessRangeInfo> getRangeInfoSpecification(RangeInfoCondition condition){
        return new Specification<BusinessRangeInfo>() {
            @Override
            public Predicate toPredicate(Root<BusinessRangeInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (condition.getBusinessGroupId() != null) {
                    predicates.add(criteriaBuilder.equal(root.get("businessGroupId").as(Long.class) , condition.getBusinessGroupId()));
                }
                if (StringUtils.isNotBlank(condition.getChannelCode())) {
                    predicates.add(criteriaBuilder.equal(root.get("channelCode").as(String.class) , condition.getChannelCode()));
                }
                if (StringUtils.isNotBlank(condition.getRegionCode())) {
                    predicates.add(criteriaBuilder.equal(root.get("regionCode").as(Long.class) , condition.getRegionCode()));
                }
                if (condition.getProjectId() != null) {
                    predicates.add(criteriaBuilder.equal(root.get("projectId").as(Long.class) , condition.getProjectId()));
                }

                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createTime")));

                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }

    /**
     * 获取前两条数据
     *
     * @param businessGroupId
     * @return
     */
    public List<BusinessRangeInfo> findByGroupId(Long businessGroupId){
        return rangeInfoRepository.findTop2ByBusinessGroupIdOrderByCreateTimeDesc(businessGroupId);
    }

    /**
     * 根据业务组ID获取业务范围数据总数
     *
     * @param businessGroupId
     * @return
     */
    public Long countByBusinessGroupId(Long businessGroupId){
        return rangeInfoRepository.countByBusinessGroupId(businessGroupId);
    }

    /**
     * 保存业务范围
     *
     * @param businessRangeInfo
     * @return
     */
    public BusinessRangeInfo save(BusinessRangeInfo businessRangeInfo){
        Date date = new Date();
        businessRangeInfo.setCreateTime(date);
        businessRangeInfo.setUpdateTime(date);
        businessRangeInfo.setStates(GoalStatusEnum.VALID.getCode());
        return rangeInfoRepository.save(businessRangeInfo);
    }

    /**
     * 根据ID获取当前记录
     *
     * @param id
     * @return
     */
    public BusinessRangeInfo findById(Long id) {
        return rangeInfoRepository.findOne(id);
    }

    /**
     * 删除业务范围
     *
     * @param rangeInfo
     */
    public void deleted(BusinessRangeInfo rangeInfo) {
        if (Objects.isNull(rangeInfo)) {
            throw new BusinessException("数据不合法");
        }
        rangeInfoRepository.delete(rangeInfo);
    }

    /**
     * 批量删除业务范围
     * @param rangeInfoList
     */
    @Transactional
    public void deletedList(List<BusinessRangeInfo> rangeInfoList){
        rangeInfoRepository.delete(rangeInfoList);
    }

    /**
     * 根据业务组ID修改业务范围状态
     *
     * @param businessGroupId
     */
    @Transactional
    public void deletedByGroupId(Long businessGroupId){
        rangeInfoRepository.deletedByGroupId(businessGroupId);
    }

    /**
     * 保存数据
     * @param businessRangeInfoList
     */
    public void saveAll(List<BusinessRangeInfo> businessRangeInfoList){
        rangeInfoRepository.save(businessRangeInfoList);
    }
}
